package org.example.mqtt;

import com.hivemq.client.mqtt.datatypes.MqttQos;
import com.hivemq.client.mqtt.mqtt5.Mqtt5AsyncClient;
import com.hivemq.client.mqtt.mqtt5.Mqtt5Client;

import java.nio.charset.StandardCharsets;
import java.util.concurrent.ExecutionException;

/**
 * @author scout.du
 * @date 2025/10/14 11:06
 **/
public class Client5V2Start {

    public static void main(String[] args) throws ExecutionException, InterruptedException {

        // 1. 创建异步 MQTT 客户端（MQTT 3）
//        Mqtt3AsyncClient client = Mqtt3Client.builder()
//                .identifier("java-client-01")   // Client ID
//                .serverHost("localhost")        // Broker 地址
//                .serverPort(1883)               // WebSocket 端口
//                .buildAsync();

        Mqtt5AsyncClient client = Mqtt5Client.builder()
                .serverHost("localhost")
                .serverPort(1883)
                .build().toAsync();

        // ensure we continue the previous session meaning we will get the messages that were sent to the broker while we were offline
        client.connectWith().cleanStart(false).noSessionExpiry().send().get();

        client.subscribeWith()
                .topicFilter("$share/XID_MDK_SCOUT/EMAIL/+/XID_BS_MDK2/Porsche/MDKv2/#")
                .qos(MqttQos.AT_LEAST_ONCE)
                .callback(publish -> {
                    // publish 类型是 Mqtt5Publish
                    String topic = publish.getTopic().toString();
                    String payload = new String(publish.getPayloadAsBytes(), StandardCharsets.UTF_8);
                    System.out.println("📩 收到消息：topic = " + topic + "，payload = " + payload);
                })
                .send().get();

        // 阻止主线程退出（仅测试用）
        try {
            Thread.sleep(500000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        // 5. 断开连接
        client.disconnect();
    }
}
